package com.api.controller;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.api.entity.Api;
import com.api.entity.Module;
import com.api.service.ApiService;
import com.api.service.ModuleService;
import com.api.util.ApiJson;

@Controller
@RequestMapping("/module")
public class ModuleController extends BaseController {

	@Autowired
	private ApiService apiService;
	@Autowired
	private ModuleService moduleService;

	@RequestMapping("/getMenusInfo")
	@ResponseBody
	public ApiJson getMenusInfo(String projectId) {
		ApiJson json = new ApiJson();
		if (StringUtils.isBlank(projectId)) {
			json.setCode("-1");
			json.setIsSuccess(false);
			json.setMessage("project_id不能为空");
			return json;
		}
		List<Module> moduleList = moduleService.getModuleByProjectId(projectId);
		if (moduleList != null && moduleList.size() > 0) {
			List<Api> apiList = apiService.getApiList(projectId);
			json.putDataMap("moduleList", moduleList);
			json.putDataMap("apiList", apiList);
		} else {
			// json.putDataMap("moduleList", null);
			// json.putDataMap("apiList", null);
		}
		return json;

	}

	@RequestMapping("/saveOrEditModule")
	public String saveOrEditModule(Model model, String moduleId, String project_id) {
		model.addAttribute("moduleId", moduleId);
		model.addAttribute("project_id", project_id);
		if (StringUtils.isNotEmpty(moduleId)) {
			model.addAttribute("module", moduleService.getModuleById(moduleId));
		} else {
			model.addAttribute("module",new Module());
		}
		return "module/saveOrEdit";
	}

	@RequestMapping("/doSaveOrEditModule")
	@ResponseBody
	public ApiJson doSaveOrEditModule(Module module) {
		ApiJson apiJson = new ApiJson();
		if (StringUtils.isNotEmpty(module.getId())) {
			// edit
			moduleService.update(module);
			apiJson.setMessage("编辑成功");
		} else {
			// save
			moduleService.add(module);
			apiJson.setMessage("添加成功");
		}
		return apiJson;
	}

	@RequestMapping("/deleteModule")
	@ResponseBody
	public ApiJson deleteModule(String module_id) {
		ApiJson apiJson = new ApiJson();
		if (StringUtils.isEmpty(module_id)) {
			apiJson.setMessage("模块id不能为空");
			apiJson.setIsSuccess(false);
			return apiJson;
		}
		Module module = moduleService.getModuleById(module_id);
		if (module != null) {
			module.setStatus(0);
			moduleService.update(module);
		}
		apiJson.setMessage("删除成功");
		return apiJson;
	}
}
